package com.friends.utils.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池 配置
 */
@Configuration
public class ExecutorConfig {

    private static final int KEEP_ALIVE_SECONDS_FIFTEEN = 60 * 15;
    private static final String PREFIX_LOGGING_ASYNC = "-logSaveExecutor-";

    @Bean
    public Executor logExecutor() {
        ThreadPoolTaskExecutor executor =
            initExecutor(4, 8, KEEP_ALIVE_SECONDS_FIFTEEN,
                50, PREFIX_LOGGING_ASYNC, new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        executor.initialize();
        return executor;
    }

    /**
     * 初始一个线程池
     *
     * @param corePoolSize 核心线程数
     * @param maxPoolSize 最大线程数
     * @param keepAliveSeconds 活跃时间
     * @param queueCapacity 队列大小
     * @param threadNamePrefix 线程池中的线程的名称前缀
     * @param rejectedExecutionHandler 饱和策略 (1) ThreadPoolExecutor.AbortPolicy
     *            默认的,处理程序遭到拒绝将抛出运行时RejectedExecutionException; (2) ThreadPoolExecutor.CallerRunsPolicy 线程调用运行该任务的
     *            execute 本身。 此策略提供简单的反馈控制机制，能够减缓新任务的提交速度 (3) ThreadPoolExecutor.DiscardPolicy 不能执行的任务将被删除; 4)
     *            ThreadPoolExecutor.DiscardOldestPolicy 如果执行程序尚未关闭， 则位于工作队列头部的任务将被删除，然后重试执行程序（如果再次失败，则重复此过程）。
     * @return
     */
    private ThreadPoolTaskExecutor initExecutor(int corePoolSize, int maxPoolSize, int keepAliveSeconds,
        int queueCapacity, String threadNamePrefix, RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        return executor;
    }
}
